#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

typedef struct{
    int x;
    int y;
    int z;
}Vector;

Vector Vector_contruct(int a,int b,int c){

    Vector v;
    v.x = a;
    v.y = b;
    v.z = c;

    return v;
}

void Vector_print(char * name,Vector v){

    printf("%s is (%d %d %d).\n",name,v.x,v.y,v.z);
}
void Vector_writet(char * filename,Vector v){

    FILE * fptr = NULL;
    fptr = fopen(filename,"w"); // file must exist
    if(NULL == fptr){

        printf("Vector_writet fopen failed.\n");
        return;
    }
    fprintf(fptr,"%d %d %d",v.x,v.y,v.z);
    fclose(fptr);
}

Vector Vector_readt(char * filename){

    Vector v = Vector_contruct(0,0,0);
    FILE * fptr = NULL;
    fptr = fopen(filename,"r");
    if(NULL == fptr){

        printf("Vector_readt fopen failed.\n");
        return v;
    }
    // 按照数字的格式读取数字 并 按照%d的总计返回
    if(fscanf(fptr,"%d %d %d",&v.x,&v.y,&v.z)!=3){

        printf("fprintf failed.\n");
    }
    fclose(fptr);
    return v;
}

void Vector_writeb(char * filename,Vector v){

    FILE * fptr = NULL;
    fptr = fopen(filename,"w");
    if(NULL == fptr){

        printf("Vector_writeb fopen failed.\n");
        return;
    }
    if(fwrite(&v,sizeof(Vector),1,fptr)!=1){

        printf("fwrite failed.\n");
    }
    fclose(fptr);
}

Vector Vector_readb(char * filename){

    Vector v;
    FILE * fptr = NULL;
    fptr = fopen(filename,"r");
    if(NULL == fptr){

        printf("Vector_readb fopen failed.\n");
        return v;
    }
    if(fread(&v,sizeof(Vector),1,fptr)!=1){

        printf("fread failed.\n");
    }
    fclose(fptr);
    return v;
}

int main(int argc,char * argv){

    Vector v1 = Vector_contruct(13,206,-549);
    Vector v2 = Vector_contruct(-15,8762,1897);
    Vector_print("v1",v1);
    Vector_print("v2",v2);
    printf("===========================================.\n");
    Vector_writet("vectort.dat",v1);
    v2 = Vector_readt("vectort.dat");

    Vector_print("v1",v1);
    Vector_print("v2",v2);

    v1 = Vector_contruct(2089,-3357,1234);
    v2 = Vector_contruct(8761,0,1784);
    printf("===========================================.\n");
    Vector_print("v1",v1);
    Vector_print("v2",v2);

    Vector_writeb("vectorb.dat",v1);
    v2 = Vector_readb("vectorb.dat");
    printf("===========================================.\n");
    Vector_print("v1",v1);
    Vector_print("v2",v2);


    return EXIT_SUCCESS;
}



